package com.yuchen.bearrecord.service.impl;

import com.yuchen.bearrecord.config.RequestHeaderContext;
import com.yuchen.bearrecord.config.Result;
import com.yuchen.bearrecord.dto.DrugDto;
import com.yuchen.bearrecord.dto.DrugSelectDto;
import com.yuchen.bearrecord.dto.ExpireDrugDto;
import com.yuchen.bearrecord.dto.UserDto;
import com.yuchen.bearrecord.entity.Drug;
import com.yuchen.bearrecord.entity.User;
import com.yuchen.bearrecord.repository.DrugRepository;
import com.yuchen.bearrecord.repository.PrescriptionRepository;
import com.yuchen.bearrecord.repository.UserRepository;
import com.yuchen.bearrecord.service.DrugService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
public class DrugServiceImpl implements DrugService {

    @Resource
    private UserRepository userRepository;
    @Resource
    private PrescriptionRepository prescriptionRepository;
    @Resource
    private DrugRepository drugRepository;

    @Override
    public Result getDrugDetail(Long id) {
        UserDto userDto = RequestHeaderContext.getInstance().getUserDto();
        HashMap<Object, Object> map = new HashMap<>(1);
        Drug drugDetail = drugRepository.findDrugById(id);
        if (userRepository.findByOpenid(userDto.getOpenid()).getType() == 0 && !drugDetail.getUser().getOpenid().equals(userDto.getOpenid())) {
            return Result.error("非法访问");
        } else {
            map.put("drugDetail", drugDetail);
            return Result.ok(map);
        }
    }

    @Override
    public Result getDrugList() {
        UserDto userDto = RequestHeaderContext.getInstance().getUserDto();
        User user = userRepository.findByOpenid(userDto.getOpenid());
        HashMap<Object, Object> map = new HashMap<>(1);
        List<DrugDto> drugList = drugRepository.findDrugsByUser(user);
        map.put("drugList", drugList);
        return Result.ok(map);
    }

    @Override
    public Result getExpireDrugs() {
        UserDto userDto = RequestHeaderContext.getInstance().getUserDto();
        User user = userRepository.findByOpenid(userDto.getOpenid());
        HashMap<Object, Object> map = new HashMap<>(1);
        List<ExpireDrugDto> expiredDrugs = drugRepository.findExpiredDrugs(user, LocalDate.now());
        map.put("expiredDrugs", expiredDrugs);
        LocalDate start7Date = LocalDate.now();
        LocalDate end7Date = start7Date.plusDays(7); // 明天起的7天后
        List<ExpireDrugDto> day7List = drugRepository.findExpiringDrugs(user, start7Date, end7Date);
        map.put("day7List", day7List);
        return Result.ok(map);
    }

    @Override
    public Result searchDurgs(String keyword) {
        UserDto userDto = RequestHeaderContext.getInstance().getUserDto();
        User user = userRepository.findByOpenid(userDto.getOpenid());
        HashMap<Object, Object> map = new HashMap<>(1);
        List<Drug> searchList = drugRepository.findDrugsByKeyword(user, keyword);
        map.put("searchList", searchList);
        return Result.ok(map);
    }

    @Override
    public Result addDrug(Drug drug) {
        if (!drugRepository.findDrugsByDrugName(drug.getDrugName()).isEmpty()) {
            return Result.error("药名重复");
        }
        UserDto userDto = RequestHeaderContext.getInstance().getUserDto();
        User user = userRepository.findByOpenid(userDto.getOpenid());
        drug.setUser(user);
        drugRepository.saveAndFlush(drug);
        return Result.ok();
    }

    @Override
    public Result deleteDrug(Long id) {
        try {
            drugRepository.deleteDrugById(id);
        } catch (DataAccessException e) {
            return Result.error("该药品已被关联，不能删除");
        }
        return Result.ok();
    }

    @Override
    public Result updateDrug(Drug drug) {
        try {
            Drug drugById = drugRepository.findDrugById(drug.getId());
            drugById.setDrugName(drug.getDrugName());
            drugById.setIngredient(drug.getIngredient());
            drugById.setIndication(drug.getIndication());
            drugById.setSpecification(drug.getSpecification());
            drugById.setUsageDosage(drug.getUsageDosage());
            drugById.setPlace(drug.getPlace());
            drugById.setExpireDate(drug.getExpireDate());
            drugById.setSurplus(drug.getSurplus());
            drugById.setImg(drug.getImg());
            drugRepository.save(drugById);
        } catch (Exception e) {
            return Result.error(drug.getId() + "修改失败");
        }
        return Result.ok();
    }

    @Override
    public Result updateDrugSurplus(Drug drug) {
        try {
            Drug drugById = drugRepository.findDrugById(drug.getId());
            drugById.setSurplus(drug.getSurplus());
            drugRepository.save(drugById);
        } catch (Exception e) {
            return Result.error(drug.getId() + "修改失败");
        }
        return Result.ok();
    }

    @Override
    public Result getUserDrugList(String openid) {
        UserDto userDto = RequestHeaderContext.getInstance().getUserDto();
        HashMap<String, Object> map = new HashMap<>();
        User user0 = userRepository.findByOpenid(userDto.getOpenid());
        if (user0.getType() == 0) {
            return Result.error("当前用户不是管理员！");
        }
        User user = userRepository.findByOpenid(openid);
        List<DrugDto> drugList = drugRepository.findDrugsByUser(user);
        map.put("drugList", drugList);
        return Result.ok(map);
    }

    @Override
    public Result updateUserDrug(Drug drug) {
        if (checkAdmin()||checkProAdmin()) return Result.error("当前用户不是超级管理员！");
        return updateDrug(drug);
    }

    @Override
    public Result deleteUserDrug(Long id) {
        if (checkAdmin()) return Result.error("当前用户不是管理员！");
        return deleteDrug(id);
    }

    @Override
    public Result clearDrugs() {
        UserDto userDto = RequestHeaderContext.getInstance().getUserDto();
        User user0 = userRepository.findByOpenid(userDto.getOpenid());
        try {
            prescriptionRepository.deleteAllByUser(user0);
            drugRepository.deleteAllByUser(user0);
        }catch (Exception e){
            return Result.error("清除失败");
        }
        return Result.ok();
    }

    @Override
    public Result getSelectDrugs() {
        UserDto userDto = RequestHeaderContext.getInstance().getUserDto();
        User user = userRepository.findByOpenid(userDto.getOpenid());
        HashMap<Object, Object> map = new HashMap<>(1);
        List<DrugSelectDto> selectDrugs = drugRepository.findAllByUser(user);
        map.put("selectDrugs", selectDrugs);
        return Result.ok(map);
    }

    public boolean checkAdmin() {
        UserDto userDto = RequestHeaderContext.getInstance().getUserDto();
        User user0 = userRepository.findByOpenid(userDto.getOpenid());
        return user0.getType() == 0;
    }

    public boolean checkProAdmin() {
        UserDto userDto = RequestHeaderContext.getInstance().getUserDto();
        User user0 = userRepository.findByOpenid(userDto.getOpenid());
        return user0.getType() != 2;
    }

}
